昨天引用了許多函式庫,今天就來使用他們所提供的功能,真正來實作chatroom內容吧~~
spinner.show(in: view)
首先我們在畫面加上spinner的元件。
接著在之前的程式中,加上更多判斷spinner的邏輯。
當該使用者存在時,就把spinner dismiss掉。
DatabaseManager.shared.userExists(with: email, completion: { [weak self] exists in
guard let strongSelf = self else { // prevent from memory leak
return
}
DispatchQueue.main.async {
strongSelf.spinner.dismiss()
}
guard !exists else {
strongSelf.alertUserLoginError(message: "user for that email address already exists")
return
}
FirebaseAuth.Auth.auth().createUser(withEmail: email, password: password, completion: { authResult, error in
guard authResult != nil, error == nil else {
print("error creating user")
return
}
// data entry
DatabaseManager.shared.insertUser(with: ChatAppUser(firstName: firstname,
lastName: lastname,
emailAddress: email))
// todo: flow check
strongSelf.navigationController?.dismiss(animated: true, completion: nil)
})
})
我們將table view的邊線,在subview load進來時顯示。
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.frame = view.bounds
}
終於進到聊天的view controller了!
首先,先引入函式庫。其中MessageKit是一個處理跟聊天相關所有行為的函式庫。
import UIKit
import MessageKit
struct Message: MessageType {
var sender: SenderType
var messageId: String
var sentDate: Date
var kind: MessageKind
}
struct Sender: SenderType {
var photoURL: String // URL
var senderId: String
var displayName: String
}
class ChatViewController: MessagesViewController {
// collection of messages
private var messages = [Message]()
private let selfSender = Sender(photoURL: "",
senderId: "1",
displayName: "Joe Smith")
override func viewDidLoad() {
super.viewDidLoad()
messages.append(Message(sender: selfSender,
messageId: "1",
sentDate: Date(),
kind: .text("Hello world message hello world message hello world message")))
messagesCollectionView.messagesDataSource = self
messagesCollectionView.messagesLayoutDelegate = self
messagesCollectionView.messagesDisplayDelegate = self
}
}
每次都會需要新增,因為我們在上面有將messagesDataSource
, messagesLayoutDelegate
, messagesDisplayDelegate
指派給自己。
因此需要新增以下幾個方法:
extension ChatViewController: MessagesDataSource, MessagesLayoutDelegate, MessagesDisplayDelegate {
func currentSender() -> SenderType {
return selfSender
}
func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
// MessageKit use section to separate every single message
return messages[indexPath.section] // a single section, per message
}
func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
return messages.count
}
}
赫然發現測試時每次都要把app從模擬器中卸載再重裝,完全是因為忘記把logout的功能加上去XDD
那明天就來實作這邊吧!
若上述內容有誤或可以改進的部分,歡迎留言以及提出任何指教~
謝謝 (´・∀・`)